package com.zzjx.db.config;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.exception.NacosException;
import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.core.parser.SqlParserHelper;
import com.redxun.common.properties.TenantProperties;
import com.zzjx.datasource.DynamicDataSourceRegister;
import com.zzjx.listener.DataSourceListener;
import org.apache.ibatis.mapping.MappedStatement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * 多租户自动配置
 *
 * @author zzjx
 * @date 2019/8/5
 */
@EnableConfigurationProperties(TenantProperties.class)
public class TenantAutoConfigure {
    @Autowired
    private TenantProperties tenantProperties;
    @Autowired
    private NacosConfigProperties nacosConfigProperties;
    @Autowired
    private DynamicDataSourceRegister dynamicDataSourceRegister;
    @Value("${spring.application.name}")
    private String applicationName;

    @Bean
    public DataSourceListener dataSourceListener() throws NacosException {
        return new DataSourceListener(nacosConfigProperties, dynamicDataSourceRegister, applicationName);
    }


    /**
     * 过滤不需要根据租户隔离的MappedStatement
     */
    @Bean
    public ISqlParserFilter sqlParserFilter() {
        return metaObject -> {
            MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject);
            return tenantProperties.getIgnoreSqls().stream().anyMatch(
                    (e) -> e.equalsIgnoreCase(ms.getId())
            );
        };
    }
}
